<?php

namespace App\Services\Iot;

use App\Model\IotLog;
use App\Model\Normal;
use Hyperf\Config\Annotation\Value;

/**
 * Created by PhpStorm.
 * User: liuta
 * Date: 2018/9/29
 * Time: 18:44
 */
class IotService1
{
    public static $mqtt = null;
    private static string $server = '123.156.229.164';
    private static int $port = 1883;
    private static ?string $username = 'admin';
    private static ?string $password = 'administrator';


    /**
     * @return \PhpMqtt\Client\MqttClient
     * @throws \PhpMqtt\Client\Exceptions\ProtocolNotSupportedException
     */
    public static function getClient()
    {
        $connectSettings = (new \PhpMqtt\Client\ConnectionSettings())
            ->setUsername(self::$username)
            ->setPassword(self::$password);
        $mqtt = new \PhpMqtt\Client\MqttClient(self::$server, self::$port);
        $mqtt->connect($connectSettings,true);
        return $mqtt;
    }

    public static function replaySomeThing($imei)
    {
        $mqtt = self::getClient();
        $msg = chr(0x3c);
        $msg .= chr(0x00);
        $msg .= chr(date('Y') - 2000);
        $msg .= chr(date('m'));
        $msg .= chr(date('d'));
        $msg .= chr(date('H'));
        $msg .= chr(date('i'));
        $msg .= chr(date('s'));
        $msg .= chr(0x05);
        $msg .= chr(0x1c);

        $mqtt->publish('/v1/device/' . $imei . '/tx', $msg, 1);
    }


    /**
     * @param       $imei string 通讯号
     * @param       $cmd  int 命令码
     * @param array $data
     *                    !!!所有参数涉及到16进制的 均转换为10进制在传递
     */
    public static function send($imei, $cmd, array $data)
    {
        //Change client name to something unique
        $connectSettings = (new \PhpMqtt\Client\ConnectionSettings())
            ->setUsername(self::$username)
            ->setPassword(self::$password);
        $mqtt = new \PhpMqtt\Client\MqttClient(self::$server, self::$port);
        $mqtt->connect($connectSettings,true);
        //LEN 单字节 CMD开始算的命令字节长度
        $len = count($data) + 3;
        //RESULT 单字节 命令是否成功, 0x01成功; 0x00失败; 0xFF无网络; 发起方固定为0x01
        $result = 0x00;
        //SUM 单字节 LEN CMD RESULT DATA的异或值
        $sum = $len ^ $cmd ^ $result;

        logger('send iot cmd', [
            'cmd'  => $cmd,
            'data' => $data,
            'len'  => $len,
            'sum'  => $sum,
        ]);

        //记录日志
        $fullData = array_merge([
            0xAA,
            $len,
            $cmd,
            $result,
        ], $data, [$sum]);
        IotLog::record($imei, IotLog::TYPE_SEND, $fullData);

        $msg = null;
            $msg = chr(0xAA); //SOP 单字节字头 固定AA
            $msg .= chr($len);
            $msg .= chr($cmd); //CMD 单字节 命令
            $msg .= chr($result);

            foreach ($data as $i => $item) {
                $msg .= chr($item);
                $sum = $sum ^ $item;
            }

            $msg .= chr($sum);

            //记录一下日志
            $strlen    = strlen($msg);
            $strSource = [];
            for ($i = 0; $i < $strlen; $i++) {

                # code..
                $strSource[] = dechex(ord(substr($msg, $i, 1)));
            }
            logger('send message ' . $imei, $strSource);


            $mqtt->publish('/v1/device/' . $imei . '/tx', $msg);
            $mqtt->disconnect();
    }

//    /**
//     * @param $sn
//     * @return bool
//     * 查询设备是否在线
//     */
//    public static function queryDeviceOnlineStatus($sn)
//    {
//
////        return (boolean) Arr::get($result, 'online');
//    }


    public static function queryDeviceStatus($imei)
    {
        self::send($imei, 0x01, [
            0x00,
        ]);
    }

    public static function stop($imei, $port)
    {
        self::send($imei, 0x0D, [
            $port,
            0x01
        ]);
    }


    public static function replayStop($imei, $port)
    {
        self::send($imei, 0x16, [
            $port,
        ]);
    }


    /**
     * @param $imei
     * @param $port
     * @param $minutes
     * @param $fee float 钱 单位:元
     */
    public static function start($imei, $port, $minutes, $fee)
    {
        Normal::logger('start params','iotevent','info');
        $duration1 = floor($minutes / 256);
        $duration2 = $minutes % 256;

        $fee1 = floor($fee * 10 / 256);
        $fee2 = floor($fee * 10 % 256);

        self::send($imei, 0x04, [
            //端口号
            $port,

            //费用
            $fee1,
            $fee2,

            //时间
            $duration1,
            $duration2,
        ]);
    }


    public static function readParams($imei)
    {
        self::send($imei, 0x1E, [
            0x00
        ]);
    }

    public static function queryMoney($imei)
    {
        self::send($imei, 0x07, [
            0x00
        ]);
    }


    public static function updateParams($imei, array $params)
    {
        self::send($imei, 0x18, $params);
    }


    public static function readPower($imei,$port){
        self::send($imei,0x15, [$port]);
    }

}
